package com.ruoyix.ai.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.Data;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
public class ChatController {

    private final WebClient webClient = WebClient.builder()
        .baseUrl("https://ark.cn-beijing.volces.com")
        .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer f9c1148b-26fc-4c92-8977-fca871de1af3")
        .build();

    @SaIgnore
    @PostMapping(value = "/api/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chat(@RequestBody ChatRequest request) {
        return webClient.post()
            .uri("/api/v3/chat/completions")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(Map.of(
                "model", "doubao-1-5-pro-256k-250115",
                "stream", true,
                "messages", List.of(
                    Map.of("role", "system", "content", "You are a helpful assistant."),
                    Map.of("role", "user", "content", request.getQuestion())
                )
            ))
            .retrieve()
            .bodyToFlux(String.class)
            .filter(text -> !text.trim().isEmpty()) // 过滤空行
            .map(text -> {
                System.out.println(text);
                return text;}
            );
    }





    @Data
    static class ChatRequest {
        private String question;
    }
}
